package com.etung.iot.demo.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {
    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static String xorEncrypt(String data,String secret){
        byte[] b1 = data.getBytes();
        byte[] b2 = secret.getBytes();
        byte[] out = new byte[b1.length];
        for(int i=0; i< b1.length;i++){
            out[i] = (byte) (b1[i] ^ b2[i% b2.length]);
        }
        return new String(out);

    }

    /**
     * 随机数
     * @param place 定义随机数的位数
     */
    public static String randomGen(int place) {
        String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789";
        StringBuffer sb = new StringBuffer();
        Random rd = new Random();
        for(int i=0;i<place;i++) {
            sb.append(base.charAt(rd.nextInt(base.length())));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
//        String originString= "abc123";
//        System.out.println(stringToMD5(originString));
        System.out.println(stringToMD5(xorEncrypt("123|timestamp12121","e99a18c428cb")));
    }

}
